package v1

import (
	"daily-blog/global"
	"daily-blog/model"
	"daily-blog/pkg"
	"daily-blog/service"
	"github.com/gin-gonic/gin"
)

func CreateUser(c *gin.Context) {
	var user model.User
	if err := c.ShouldBindJSON(&user); err != nil {
		pkg.FailWithMessage("参数错误", c)
		global.GVA_LOG.Error(err.Error())
		return
	}
	if ok := service.CreateUser(&user); !ok {
		pkg.Fail(c)
		return
	}
	pkg.Ok(c)
}

// Login 登录
func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		pkg.FailWithMessage("账号密码为空", c)
		return
	}
	//查询用户是否存在
	userId, ok := service.GetUserByNamePwd(username, password)
	if !ok {
		pkg.FailWithMessage("登录失败", c)
		return
	}
	// 生成token
	token, err := pkg.CreateToken(userId)
	if err != nil {
		pkg.Fail(c)
		global.GVA_LOG.Error(err.Error())
		return
	}
	pkg.OkWithData(token, c)
}
